package org.opentcs.kernel.extensions.servicewebapi.jjwc;

import java.io.*;
import java.nio.charset.StandardCharsets;
import org.opentcs.access.to.model.PlantModelCreationTO;
import org.opentcs.util.persistence.v004.V004PlantModelTO;
import org.opentcs.util.persistence.v004.V004TOMapper;

/**
 * 该模块用于将xml文件写入到文件系统
 */
public class FileWriter {

  public void writeFile(PlantModelCreationTO plantModel, File file)
      throws IOException {
    String fileEnding = "xml";
    File outFile = file.getName().endsWith(fileEnding)
                   ? file
                   : new File(file.getParentFile(),
                              file.getName() + "." + fileEnding);

    writeModel(plantModel, outFile);
  }

  public void writeModel(PlantModelCreationTO model, File file)
      throws IOException {
    try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),
                                                                   StandardCharsets.UTF_8))) {
      V004TOMapper mapper = new V004TOMapper();
      V004PlantModelTO mappedModel = mapper.map(model);
      mappedModel.toXml(writer);
    }
  }


}
